#coding=utf-8
'''
Created on 2013年7月29日

@author: xuben
官网预登录
'''

from ..common import GameConfig, HttpService, Logger
import hashlib
import json
import urllib

#官网认证需要的一些东西
ts = 0
key = 0
#预登录是否成功
preLoginSuccess = False

'''
官网预登录
@param reconnect: 是否重连
'''
def preLogin(reconnect):
    if reconnect:
        step6()
    else:
        step1()
    global preLoginSuccess
    return preLoginSuccess

#官网预登录步骤1 get
def step1():
    url = GameConfig.ast_site_url + '/jsonp.action'
    params = {}
    params['jsoncallback'] = 'jsonp1375087617192'
    params['funName'] = 'indexLogin'
    params['username'] = GameConfig.user_name
    if not GameConfig.encrypted:
        GameConfig.password = hashlib.md5(GameConfig.password).hexdigest()
    params['password'] = GameConfig.password
    encode_params = urllib.urlencode(params)
    url = url + '?' + encode_params
    step1ResponseStr = HttpService.send(url)
#     print step1ResponseStr
    step2(step1ResponseStr)

#官网预登录步骤2 post
def step2(step1ResponseStr):
    #去掉jsonp的包装
    leftParen = step1ResponseStr.find('(')
    rightParen = step1ResponseStr.rfind(')')
    leftBrace = step1ResponseStr.find('{')
#     rightBrace = step1ResponseStr.rfind('}')
    secondLeftParen = step1ResponseStr.find('{', leftBrace+1)
    secondRightParen = step1ResponseStr.find('}')
    #获取jsonp回调的参数
    step1JsonStr = step1ResponseStr[leftParen+1:rightParen]
    #将参数转换成json对象
    step1JsonObj = json.loads(step1JsonStr);
    url = GameConfig.gcld_site_url + '/ssoLogin.xhtml'
    params = {'isgameLogin':"true"}
    global ts
    ts = params['ts'] = step1JsonObj['ts']
    global key
    key = params['key'] = step1JsonObj['key']
    params['userJson'] = step1ResponseStr[secondLeftParen:secondRightParen+1]
    encode_params = urllib.urlencode(params)
    HttpService.send(url, 'post', encode_params)
    step3()

#官网预登录步骤3 get
def step3():
    url = GameConfig.gcld_site_url + '/loginsucc.xhtml'
    params = {'isintro':"false"}
    params['tourl'] = GameConfig.gcld_site_url + '/index.html'
    encode_params = urllib.urlencode(params)
    url = url + '?' + encode_params
    HttpService.send(url)
    step4()

#官网预登录步骤4 get
def step4():
    url = GameConfig.gcld_site_url + '/index.html'
    HttpService.send(url)
    step5()

#官网预登录步骤5 get
def step5():
    url = GameConfig.gcld_site_url + '/getsession.xhtml'
#     0.41639327950451865
    params = {'x':0.4975837136153132, 'isgameLogin':'true', 'top':1, 'gameid':'gcld', 'source':''}
    encode_params = urllib.urlencode(params)
    url = url + '?' + encode_params
    HttpService.send(url)
    step6()

#官网预登录步骤6 get
def step6():
    url = GameConfig.gcld_site_url + '/gm.xhtml'
    params = {'gid':'gcld', 'server':1}
    encode_params = urllib.urlencode(params)
    url = url + '?' + encode_params
    HttpService.send(url)
    #获取跳转的url
    url = GameConfig.gcld_site_url + '/start_game.xhtml'
    params = {'gid':'gcld', 'server':1}
    encode_params = urllib.urlencode(params)
    url = url + '?' + encode_params
    responseStr = HttpService.send(url)
    if responseStr != None:
        step7(responseStr)
    else:
        Logger.log("预登录step6获取跳转url失败", Logger.LOGGER_LOGIN)

#官网预登录步骤7 get
def step7(responseStr):
    redirectUrl = None
    searchStartIndex = responseStr.find('window.location.href')
    if searchStartIndex >= 0:
        leftQuoteIndex = responseStr.find('"', searchStartIndex)
        if leftQuoteIndex >= 0:
            rightQuoteIndex = responseStr.find('"', leftQuoteIndex+1)
            if rightQuoteIndex >= 0:
                redirectUrl = responseStr[leftQuoteIndex+1:rightQuoteIndex]
    if redirectUrl != None:
        step8(redirectUrl)
    else:
        Logger.log("预登录step7获取跳转url失败", Logger.LOGGER_LOGIN)

#官网预登录步骤8 get
def step8(url):
    HttpService.send(url)
    for cookie in HttpService.cookiejar:
        if cookie.name == 'REIGNID':
            GameConfig.USER_KEY = cookie.value
            break
    global preLoginSuccess
    preLoginSuccess = True
#     print HttpService.cookiejar._cookies['s1.gc.aoshitang.com']['/root']['REIGNID']